﻿using System.ComponentModel;
using System.Diagnostics;
using System.Timers;
using System.Xml.Serialization;

namespace TaskManager
{
    /// <summary>
    /// Class is for retrieving the current running processes of the system
    /// Processes are stored in a Process-Array 
    /// Every 1000ms the Processes are updated
    /// </summary>

    [XmlRoot("XMLDocRoot")]
    public class ProcessRetriever : INotifyPropertyChanged
    {

        [XmlArray("Processes")]
        [XmlArrayItem("ListItem")]
        private Process[] processes = null;
        public event PropertyChangedEventHandler PropertyChanged;


        private void NotifyPropertyChanged(string str)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(str));
            }
        }


        public static ProcessRetriever CreateNewProcessReciever()
        {
            return new ProcessRetriever();
        }




        public Process[] Processes
        {
            get { return this.processes; }
            set
            {
                if (value != this.processes)
                {
                    this.processes = value;
                    NotifyPropertyChanged("Processes");
                }
            }
        }



        private ProcessRetriever()
        {
            Timer timer = new Timer(1000);
            timer.Elapsed += new ElapsedEventHandler(timer_elapsed);
            timer.Enabled = true;
            timer.Start();
        }

        private void timer_elapsed(object sender, ElapsedEventArgs args)
        {
            RetrieveProcesses();
        }


        private void RetrieveProcesses()
        {

            this.Processes = Process.GetProcesses();

        }


        public void CloseProcess(Process name)
        {

            foreach (Process p in processes)
            {
                if (p == name)
                {
                    p.Kill();
                }
            }
        }





    }
}
